'''

Refs:
http://www.larsen-b.com/Article/184.html
http://stackoverflow.com/questions/1147653/python-xlib-catch-send-mouseclick
http://tronche.com/gui/x/xlib/input/XGrabKey.html


https://github.com/pepijndevos/PyMouse


'''

from Xlib.display import Display
from Xlib import X
from Xlib.protocol import rq
#import oss

# custom keys from my dell D400 Laptop
A = 176
S = 174

keys = [A,S]

def handle_event(aEvent):
    keycode = aEvent.detail
    if aEvent.type == X.KeyPress:
        if keycode == A:
            print "CATCH A"
        elif keycode == S:
            print "CATCH S"

def main():
    print 1
    # current display
    disp = Display()
    root = disp.screen().root

    print 2
    # we tell the X server we want to catch keyPress event
    root.change_attributes(event_mask = X.KeyPressMask)

    print 3
    for keycode in keys:
        root.grab_key(X.AnyKey, X.AnyModifier, 1, X.GrabModeAsync, X.GrabModeAsync)

    print 4
    i = 0
    while i < 100:
        i += 1
        print '.'
        rq.EventField(None).parse_binary_value(data, record_dpy.display, None, None)
        print '----------'
        event = root.display.next_event()
        print 5
        handle_event(event)
        print 6

def threaded_rec():
    print 1
    local_dpy = Display()
    print 2
    record_dpy = Display()
    
    if not record_dpy.has_extension("RECORD"):
        print "RECORD extension not found"
        sys.exit(1)
    r = record_dpy.record_get_version(0, 0)
    print "RECORD extension version %d.%d" % (r.major_version, r.minor_version)

if __name__ == '__main__':
    if 1:
        import thread
        thread.start_new_thread(thread_test,(1,))
    else:
        main()
